from flask import g

from Info import constants,redis_store
from Info.models import User, News, Category
from Info.utils.commons import user_login_data
from Info.utils.response_code import RET
from . import index_blue
import logging
from flask import current_app, jsonify,render_template,session,request

# 获取新闻列表
"""
1.获取参数
2.参数类型转换
3.分页查询
4。获取分页对象身上属性
5.将对象列表转换成字典列表
6.拼接数据，返回响应
"""
@index_blue.route("/newslist")
def new_list():
    # 1.获取参数
    cid = request.args.get("cid","1")
    page = request.args.get("page","1")
    per_page = request.args.get("per_page","10")
    # 2.参数类型转换
    try:
        page = int(page)
        per_page = int(per_page)
    except Exception as e:
        current_app.logger.error(e)
        page = 1
        per_page = 10
    # 3.分页查询
    try:
        query_condition = ""
        if cid != "1":
            query_condition = News.category_id == cid
        paginate = News.query.filter(query_condition).order_by(News.create_time.desc()).paginate(page,per_page,False)
    except Exception as e:
        current_app.logger.error(e)
        return jsonify(errno=RET.DBERR,errmsg="新闻获取失败")
    # 4.获取分页对象身上属性
    totalPage = paginate.pages
    currentPage = paginate.page
    items = paginate.items

    # 5.将对象列表转换成字典列表
    newsList = []
    for item in items:
        newsList.append(item.to_dict())
    # 6.拼接数据，返回响应
    return jsonify(errno=RET.OK,errmsg="获取成功",totalPage = totalPage,currentpage = currentPage,newsList = newsList)

"""
功能描述: 退出登陆
请求路径: /passport/logout
请求方式: POST
请求参数: 无
返回值: errno, errmsg
"""

@index_blue.route('/',methods=["GET","POST"])
@user_login_data
def show_index():
    # 获取用户登陆状态
    # user_id = session.get("user_id")
    #
    # # 获取用户登陆数据
    # user = None
    # if user_id:
    #     try:
    #         user = User.query.get(user_id)
    #     except Exception as e:
    #         current_app.logger.error(e)


    #根据
    try:
        news = News.query.order_by(News.clicks.desc()).limit(constants.CLICK_RANK_MAX_NEWS).all()
    except Exception as e:
        current_app.logger.error(e)
        return jsonify(erron=RET.DBERR,errmsg="新闻查询失败")

    # 讲新闻对象列表转成字典列表
    click_news_list = []
    for new in news:
        click_news_list.append(new.to_dict())
    try:
        categories = Category.query.all()
    except Exception as e:
        current_app.logger.error(e)
        return jsonify(errno=RET.DBERR ,errmsg="分类查询失败")

    # 将分类对象列表转成字典列表
    category_list = []
    for category in categories:
        category_list.append(category.to_dict())
    # 携带用户数据渲染到页面中
    data = {
        "user_info":g.user.to_dict() if g.user else "",
        "click_news_list":click_news_list,
        "category_list":category_list

    }

    return render_template("news/index.html", data=data)


@index_blue.route("/favicon.ico")
def web_logo():
    return current_app.send_static_file("news/favicon.ico")